import asyncio
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
from pydantic import AnyUrl


async def main():
    print("客户端开始启动")
    server_url = "http://127.0.0.1:8000/mcp"
    print("请先输入令牌信息,格式是 _token_001")
    # token = input().strip()
    token = "token_001"
    # if not token.startswith("_token_"):
    #    print("令牌格式错误，应该是_token_开头")
    #    return
    try:
        custom_headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        }
        print("尝试使用Bearer令牌认证")
        async with streamablehttp_client(server_url, headers=custom_headers) as (
            read,
            write,
            _,
        ):
            async with ClientSession(read, write) as session:
                await session.initialize()
                resources = await session.list_resources()
                print(f"受保护的资源:{[r.uri for r in resources.resources]}")
                tools = await session.list_tools()
                print(f"受保护的工具:{[t.name for t in tools.tools]}")
                resource_result = await session.read_resource(AnyUrl("user://profile"))
                texts = []
                for block in resource_result.contents:
                    texts.append(getattr(block, "text", ""))
                print(f"读取资源成功", "|".join(texts))

                tool_result = await session.call_tool(
                    "get_user_data", {"user_id": "current"}
                )
                texts = []
                for block in tool_result.content:
                    texts.append(getattr(block, "text", ""))
                print(f"调用工具成功", "|".join(texts))

    except Exception as error:
        print(f"和服务器通信发生了错误:{str(error)}")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\n客户端已经停止")
    except Exception as e:
        print("客户端停止失败")
